// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	console.log('Congratulations, your extension "wanluflutterplugin" is now active!');
	const assetsCommand = vscode.commands.registerCommand('wanluflutterplugin.assets', async () => {
		const folders = vscode.workspace.workspaceFolders;
		if (!folders || folders.length <= 0) {
			return;
		}
		const rootPath = folders[0].uri.fsPath + '/assets/image';
		const rootUri = vscode.Uri.file(rootPath);
		const outputPath = folders[0].uri.fsPath + '/lib/config/assets.dart';
		const outputUri = vscode.Uri.file(outputPath);
		try {
			// 检查 assets 文件夹是否存在
			await vscode.workspace.fs.stat(rootUri);
			// 将字符串转换为驼峰命名法
			function toCamelCase(str: string): string {
				// 去除文件扩展名
				const nameWithoutExtension = str.replace(/\.[^/.]+$/, "");
				// 将分隔符（-、_、空格等）分割的单词转换为驼峰命名
				return nameWithoutExtension
					.toLowerCase()
					.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '')
					.replace(/^(.)/, c => c.toLowerCase());
			}
			// 递归遍历函数
			async function traverseDirectory(uri: vscode.Uri, indent: string = ''): Promise<string[]> {
				const result: string[] = [];
				try {
					const entries = await vscode.workspace.fs.readDirectory(uri);
					for (const [name, type] of entries) {
						const isFirstCharLetter = /^[a-zA-Z]/.test(name);
						const entryUri = vscode.Uri.file(uri.fsPath + '/' + name);
						if (type === vscode.FileType.Directory) {
							// 如果是目录，递归遍历
							if (isFirstCharLetter) {
								const subEntries = await traverseDirectory(entryUri, indent + name + '/');
								result.push(...subEntries);
							}
						} else {
							// 如果是文件，直接添加文件信息
							if (isFirstCharLetter) {
								result.push(`${indent}${name}`);
							}
						}
					}
				} catch (error) {
					result.push(`${indent}❌ 无法访问目录: ${uri.fsPath}`);
				}
				return result;
			}

			// 开始递归遍历
			const filePathList = await traverseDirectory(rootUri, 'assets/image/');
			var nameList: string[] = [];
			var content = "";
			content += `class Assets {\n`;
			content += `  Assets._();\n`;
			content += `\n`;
			filePathList.forEach(f => {
				var temp = f.split('/');
				var fileName = temp[temp.length - 1];
				var camelCaseName = toCamelCase(fileName);
				if (nameList.includes(camelCaseName)) {
					vscode.window.showErrorMessage(`文件存在重复文件名：${f},请修改文件名以避免冲突。`);
					return;
				}
				nameList.push(camelCaseName);
				content += `  static const String ${camelCaseName} = '${f}';\n`;
			});
			content += `}\n`;
			await vscode.workspace.fs.writeFile(outputUri, Buffer.from(content, 'utf8'));
			vscode.window.showInformationMessage('Wanlu Flutter Assets 生成成功！');
		} catch (error) {
			vscode.window.showErrorMessage(`无法访问 assets 文件夹: ${error}`);
		}
	});


	const pageCommand = vscode.commands.registerCommand('wanluflutterplugin.page', async (uri: vscode.Uri) => {
		// 将驼峰命名转换为下划线格式，并移除开头的下划线
		function camelToSnakeCase(str: string): string {
			return str
				.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)
				.replace(/^_/, '');
		}

		// uri 就是用户右键点击的文件夹
		if (!uri) {
			vscode.window.showErrorMessage('请选择一个文件夹');
			return;
		}

		const stat = await vscode.workspace.fs.stat(uri);
		if (stat.type !== vscode.FileType.Directory) {
			vscode.window.showErrorMessage('请选择一个文件夹');
			return;
		}

		// 获取用户输入的页面名称
		const inputString = await vscode.window.showInputBox({
			prompt: '请输入页面名称',
			placeHolder: '驼峰格式,首字母大写,不用写Page后缀,例如: OnlineRaceList'
		});

		if (!inputString) {
			return;
		}

		const rootName = camelToSnakeCase(inputString);
		const rootPath = `${uri.fsPath}/${rootName}`;
		const rootUri = vscode.Uri.file(rootPath);

		console.log(`创建页面: ${rootName} 在路径: ${rootPath}`);

		try {
			try {
				const stat = await vscode.workspace.fs.stat(rootUri);
				await vscode.workspace.fs.delete(rootUri, { recursive: true, useTrash: true });
				await vscode.workspace.fs.createDirectory(rootUri);
			} catch (error) {
				await vscode.workspace.fs.createDirectory(rootUri);
			}

			// 生成Service文件
			const serviceContent = `class ${inputString}Service {
}`;
			const serviceFileUri = vscode.Uri.file(`${rootPath}/${rootName}_service.dart`);
			await vscode.workspace.fs.writeFile(serviceFileUri, Buffer.from(serviceContent, 'utf8'));

			// 生成Repository文件
			const repositoryContent = `import '${rootName}_service.dart';

abstract class ${inputString}Repository {
}
			
class ${inputString}RepositoryImpl implements ${inputString}Repository {
}`;
			const repositoryFileUri = vscode.Uri.file(`${rootPath}/${rootName}_repository.dart`);
			await vscode.workspace.fs.writeFile(repositoryFileUri, Buffer.from(repositoryContent, 'utf8'));


			// 生成Controller文件
			const controllerContent = `import 'package:get/get.dart';

import '${rootName}_repository.dart';

class ${inputString}Controller extends GetxController {
	final ${inputString}Repository repository;

	${inputString}Controller({${inputString}Repository? repository}): repository = repository ?? ${inputString}RepositoryImpl();

	@override
	void onInit() {
		super.onInit();
		// 初始化逻辑
	}

	@override
	void onReady() {
		super.onReady();
		// 启动逻辑  网络请求
	}

	@override
	void onClose() {
		super.onClose();
		// 销毁逻辑
	}
}`;
			const controllerFileUri = vscode.Uri.file(`${rootPath}/${rootName}_controller.dart`);
			await vscode.workspace.fs.writeFile(controllerFileUri, Buffer.from(controllerContent, 'utf8'));


			// 生成页面文件
			const pageContent = `import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:component/component.dart';

import '${rootName}_controller.dart';

class ${inputString}Page extends StatefulWidget {
	factory ${inputString}Page.fromRouteSettings(RouteSettings settings) {
		// final arguments = settings.arguments as Map<String, dynamic>;
		return ${inputString}Page();
}

	const ${inputString}Page({super.key});

	@override
	State<${inputString}Page> createState() => _${inputString}PageState();	
}

class _${inputString}PageState extends State<${inputString}Page> {

	late final ${inputString}Controller _controller;

	@override
	void initState() {
		_controller = Get.put<${inputString}Controller>(${inputString}Controller());
		super.initState();
		// 初始化逻辑
	}

	@override
	void dispose() {
		super.dispose();
		Get.delete<${inputString}Controller>();
		// 销毁逻辑
	}

	@override
	Widget build(BuildContext context) {
		return WScaffold(
			appBar: WAppBar(
				title: Text('${inputString} 页面'),
				onTapLeading: () => BoostNavigator.instance.pop(),
			),
			body: Center(
				child: Text('欢迎来到 ${inputString} 页面！'),
			),
		);
	}
}`;

			const fileUri = vscode.Uri.file(`${rootPath}/${rootName}_page.dart`);
			await vscode.workspace.fs.writeFile(fileUri, Buffer.from(pageContent, 'utf8'));

			vscode.window.showInformationMessage(`${inputString} 页面创建成功！`);
		} catch (error) {
			vscode.window.showErrorMessage(`创建页面失败: ${error}`);
		}
	});

	context.subscriptions.push(assetsCommand);
	context.subscriptions.push(pageCommand);
}



// This method is called when your extension is deactivated
export function deactivate() { }
